<?php
class EmailHelper extends CApplicationComponent
{
	protected $_mail;
	
	public function init()
	{
		//error_reporting(E_STRICT);
		
		$this->_mail = new PHPMailer();
		
		if(app()->params['GLOBAL_SETTING']['EMAIL']['TYPE'] == SiteConfig::MAIL_SMTP){
			$this->_mail->IsSMTP();
			
			$this->_mail->CharSet = app()->params['GLOBAL_SETTING']['EMAIL']['CHARSET'];
			$this->_mail->SMTPDebug = app()->params['GLOBAL_SETTING']['EMAIL']['SMTP_DEBUG'];
			$this->_mail->SMTPAuth = true;
			$this->_mail->SMTPSecure = "ssl";
			$this->_mail->Host = app()->params['GLOBAL_SETTING']['EMAIL']['SMTP_HOST'];
			$this->_mail->Port = app()->params['GLOBAL_SETTING']['EMAIL']['SMTP_PORT'];
			$this->_mail->Username = app()->params['GLOBAL_SETTING']['EMAIL']['SMTP_USERNAME'];
			$this->_mail->Password = app()->params['GLOBAL_SETTING']['EMAIL']['SMTP_PASSWORD'];
		}else{
			//$this->_mail->IsMail();
			//$this->_mail->Host = "localhost";
		}
		$this->_mail->AltBody= "To view the message, please use an HTML compatible email viewer! - From www.jiucool.com"; // optional, comment out and test
		$this->_mail->SetFrom(app()->params['GLOBAL_SETTING']['EMAIL']['FROM_ADDRESS'], app()->params['GLOBAL_SETTING']['EMAIL']['FROM_NAME']);
		$this->_mail->AddReplyTo(app()->params['GLOBAL_SETTING']['EMAIL']['REPLYTO_ADDRESS'], app()->params['GLOBAL_SETTING']['EMAIL']['REPLYTO_NAME']);
			
		parent::init();
	}
	
	public function sendConfirmation($id_user = null)
	{
		if($id_user === null){
			$user = app()->user->getData();
		}else{
			$user = User::model()->findByPk($id_user);
		}
		
		$this->_mail->Subject= "Confirmation Email";
		$this->_mail->MsgHTML("
			<h2>Hello {$user->fullname}</h2>
			<p>This is just a confirmation email, to let you know the system is now successfully using the following SMTP details for system mail:</p>
			<p><b>Port:</b> {$this->_mail->Port}</p>
			<p><b>Host:</b> {$this->_mail->Host}</p>
			<p><b>Username:</b> {$this->_mail->Username}</p>
		");
		
		$this->_mail->AddAddress($user->email, $user->fullname);
		if(!$this->_mail->Send()){
			throw (new Exception('Mailer Error: ' . $this->_mail->ErrorInfo, 0));
		}
		return true;
	}
	
	public function sendResetRestrictIps($id_user = null)
	{
		if($id_user === null){
			$user = app()->user->getData();
		}else{
			$user = User::model()->findByPk($id_user);
		}
		
		$userIp = app()->request->getUserHostAddress();
		$token = self::genToken(array(
			'id_user' => $user->id_user, 
			'time' => time(), 
			'userIp' => $userIp
		));

		$this->_mail->Subject= "Reset Restrict Ips";
		$this->_mail->MsgHTML("
			<h2>Hello {$user->fullname}</h2>
			<p>A user from {$userIp} has tried to access your account, but has been blocked because this IP is not in the allowed list.  If this is you trying to regain access to your account, you may click the following link to add this IP address to the allowed list.</p>
			".CHtml::link(app()->createAbsoluteUrl('user/resetRestrictIp', array('token' => $token)), app()->createAbsoluteUrl('user/resetRestrictIp', array('token' => $token)))."<br />
			<p>Please note, for security reasons this link will expire after 1 hour.</p>
			<p>If you did not request this, you may disregard this email. you may want to block {$userIp} from your server if it does not belong to you or a colleague.</p>
		");
			
		$this->_mail->AddAddress($user->email, $user->fullname);
		if(!$this->_mail->Send()){
			throw (new Exception('Mailer Error: ' . $this->_mail->ErrorInfo, 0));
		}
		return true;
	}
	
	public function sendSuspendUser($id_user = null)
	{
		if($id_user === null){
			$user = app()->user->getData();
		}else{
			$user = User::model()->findByPk($id_user);
		}
		
		$token = self::genToken(array(
			'id_user' => $user->id_user, 
			'time' => time(), 
		));

		$this->_mail->Subject= "Unsuspend your account";
		$this->_mail->MsgHTML("
			<h2>Hello {$user->fullname}</h2>
			<p>Your account has been suspended for exceeding the maximum failed login attempts.  You may unsuspend your account by clicking the following link:</p>
			".CHtml::link(app()->createAbsoluteUrl('user/unsuspendbyemail', array('token' => $token)), app()->createAbsoluteUrl('user/unsuspendbyemail', array('token' => $token)))."<br />
			<p>Please note, for security purposes this link will expire after 1 hour.  It is recommended you review the Login Activity under your system logs, and you block any IP address you do not recognize.</p>
		");
			
		$this->_mail->AddAddress($user->email, $user->fullname);
		if(!$this->_mail->Send()){
			throw (new Exception('Mailer Error: ' . $this->_mail->ErrorInfo, 0));
		}
		return true;
	}
	
	private static $_SEP = '__=SEPSEP=__';
	private static $_IS = '__=======__';
	public static function genToken($recipe = array())
	{
		$token = array();
		foreach($recipe as $k => $v){
			$token[] = $k . self::$_IS . $v;
		}
		$token = implode(self::$_SEP, $token);
		$crypt = new Crypt();
		$token = $crypt->encrypt($token);
		$token_secure = $crypt->getKey();
		$token = $token_secure . self::$_SEP . $token;
		return base64_encode($token);
	}
	
	public static function decodeToken($token)
	{
		$token = base64_decode($token);
		@list($token_secure, $token) = explode(self::$_SEP, $token);
		if($token_secure && $token){
			$crypt = new Crypt();
			$token = $crypt->decrypt($token, $token_secure);
			$token = explode(self::$_SEP, $token);
			
			if($token){
				$ret = array();
				foreach($token as $t){
					list($k, $v) = explode(self::$_IS, $t);
					$ret[$k] = $v;
				}
				
				return $ret;
			}
		}
		return false;
	}
}